<!--
 * @Author: your name
 * @Date: 2020-08-30 14:38:00
 * @LastEditTime: 2021-02-25 15:13:10
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \adminPC\src\views\user\widget\UserCreate.vue
-->
<template>
  <div class="wrapper">
    <div>
      <JForm :form-config="dynamicValidateForm" :read="read" @handleBoxEvent="handleBoxEvent" @itemClick="fromClick" />
    </div>

    <el-dialog
      :title="dialog.title[dialog.active]"
      :visible.sync="dialog.dialogVisible"
      destroy-on-close
      append-to-body
    >
      <orgTree v-if="dialog.active==='orgId'" @treeClick="orgClick" />
      <roleTree v-if="dialog.active==='roleIds'" :user-id="userId" @treeClick="roleClick" />
    </el-dialog>
  </div>
</template>

<script>
import { add, userInfo, update } from '@/api/menber'
import { mapState, mapActions } from 'vuex'
import JForm from '@/components/JForm'

import orgTree from './orgTree'
import roleTree from './roleTree'
import { getOrgTree } from '@/api/org'
import { getList } from '@/api/role'

export default {
  components: {
    JForm,
    orgTree,
    roleTree
  },
  props: {
    userId: {
      type: String,
      default: ''
    },
    read: {
      type: Boolean,
      default: false
    }
  },
  data() {
    const userInfo = [
      {
        name: 'loginId',
        label: '用户账号',
        type: 'string',
        span: 12,
        required: true
      },
      {
        name: 'nickName',
        label: '昵称',
        type: 'string',
        span: 12,
        required: true
      },
      {
        name: 'userName',
        label: '用户姓名',
        type: 'string',
        span: 12,
        required: true
      },
      {
        name: 'telephone',
        label: '电话',
        type: 'string',
        required: false
      },
      {
        name: 'idType',
        label: '证件类型',
        type: 'option',
        span: 12,
        required: false,
        placeholder: '',
        config: {
          options: {}
        }
      },
      {
        name: 'idNo',
        label: '证件号码',
        type: 'string',
        required: false
      },
      {
        name: 'userType',
        label: '用户类型',
        type: 'option',
        required: false,
        placeholder: '',
        config: {
          options: {}
        }
      },
      {
        name: 'activationStatus',
        label: '是否激活',
        type: 'option',
        required: false,
        span: 12,
        config: {}
      },
      {
        name: 'orgId',
        label: '部门ID',
        type: 'cascader',
        span: 12,
        required: false,
        config: {
          options: [],
          props: {
            multiple: true,
            emitPath: false,
            checkStrictly: true,
            label: 'title',
            value: 'id'
          }
        }
      },
      {
        name: 'roleIds',
        label: '角色ID',
        type: 'cascader',
        required: false,
        placeholder: '',
        config: {
          options: [],
          props: {
            multiple: true,
            emitPath: false,
            checkStrictly: true,
            label: 'name',
            value: 'id'
          }
        }
      },
      {
        name: 'birthday',
        label: '出生日期',
        type: 'string',
        required: false,
        placeholder: 'date-time'
      },
      {
        name: 'email',
        label: '邮箱',
        type: 'email',
        required: false
      },
      {
        name: 'address',
        label: '地址',
        type: 'string',
        required: false
      },
      {
        name: 'postCode',
        label: '邮编',
        type: 'string',
        required: false
      }
    ]
    const dialog = {
      dialogVisible: false,
      title: { orgId: '组织机构', roleIds: '角色', userUpdate: '修改资料' },
      active: '',
      handleFilter: () => {}
    }
    return {
      dialog,
      userInfo,
      formData: {},
      serveData: {},
      orgList: [],
      roleList: []
    }
  },
  computed: {
    /* option数据处理 */
    dynamicValidateForm() {
      const data = this.userInfo
      const allValue = this.serveData
      const result = []
      data.forEach(i => {
        const { type, name } = i
        if (!i.config) {
          i.config = {}
        }
        i.config.style = { width: '49%' }
        if (type === 'option' || type === 'cascader') {
          i.config.options = this.filterOption(i)
        }
        const value = allValue[name]
        if (value) i.value = value
        result.push(i)
      })
      return result
    },
    ...mapState('dictionary', ['dic']),

    idTypeOption() {
      const data = this.dic['ID_TYPE'] || []
      const result = []
      data.forEach(i => {
        const { code, name } = i
        result.push({
          label: name,
          value: +code
        })
      })
      return result
    },
    userTypeOption() {
      const data = this.dic['USER_TYPE'] || []
      const result = []
      data.forEach(i => {
        const { code, name } = i
        result.push({
          label: name,
          value: +code
        })
      })
      return result
    },
    activationStatusOption() {
      const data = this.dic['YN01'] || []
      data.forEach(item => {
        const { code, name } = item
        item.value = +code
        item.label = name
      })
      return data
    },
    orgIdOption() {
      const data = this.orgList || []
      data.forEach(item => {
        const { code, name } = item
        item.value = +code
        item.label = name
      })
      return data
    },
    roleIdsOption() {
      const data = this.roleList || []
      data.forEach(item => {
        const { code, name } = item
        item.value = +code
        item.label = name
      })
      return data
    }
  },
  watch: {
    userId: {
      handler: function(newVal) {
        if (newVal) {
          this.getUserInfo()
        }
        if (!newVal) {
          this.serveData = {}
        }
      },
      immediate: true
    }
  },
  created() {
    this.getDictListByType('YN01')
    this.getDictListByType('ID_TYPE')
    this.getDictListByType('USER_TYPE')

    this.getOrgTree()
    this.getRoleList()
  },
  mounted() {},
  methods: {
    getOrgTree() {
      getOrgTree().then(res => {
        const { data, code } = res
        if (code === 200) {
          this.orgList = data
        }
      })
    },
    getRoleList() {
      getList().then(res => {
        console.log(res)
        const { data, code } = res
        if (code === 200) {
          this.roleList = data
        }
      })
    },
    ...mapActions('dictionary', ['getDictListByType']),
    getUserInfo() {
      userInfo(this.userId).then(result => {
        const { code, data = {}} = result
        if (code === 200) {
          this.serveData = data
        }
      })
    },
    handleBoxEvent(emitObj) {
      if (!emitObj) {
        return this.$emit('handleBoxEvent')
      }
      this.formData = emitObj
      this.$emit('handleBoxEvent', { type: 'created', target: this.formData })
      this.formData && this.submitForm()
    },
    filterOption(item) {
      const key = item.name
      return this[`${key}Option`]
    },
    async submitForm(emitObj) {
      const result = await this.createMenber()
      const { message, code } = result
      if (code === 200) {
        this.$emit('handleBoxEvent', 'created')
        return this.$message.success(message)
      }
      this.$message.error(message)
    },
    removeDomain(item) {
      var index = this.dynamicValidateForm.domains.indexOf(item)
      if (index !== -1) {
        this.dynamicValidateForm.domains.splice(index, 1)
      }
    },
    async createMenber() {
      const param = this.formData
      let runFunction = add
      /* 有 userId 是修改数据 */
      if (this.userId) {
        param.id = this.userId
        runFunction = update
      }
      let result = {}
      try {
        result = await runFunction(param)
      } catch (error) {
        console.log('客户新增', error)
      }
      return result
    },
    orgClick(target) {
      const { target: { id }} = target
      this.serveData[this.dialog.active] = id
    },
    roleClick(emitObj) {
      const { target } = emitObj
      this.serveData[this.dialog.active] = target.toString()
    },
    fromClick(item) {
      const { name } = item
      if (['orgId', 'roleIds'].includes(name)) {
        this.showDialog(name)
      }
    },
    showDialog(target) {
      this.dialog.dialogVisible = true
      this.dialog.active = target
    }
  }
}
</script>
<style lang="scss" scoped>
.wrapper{
   padding: 0px;
   margin: 0px;
}
</style>
